package radiostation;

import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListModel;
import model.Artist;
import model.MusicGroup;
import radiostation.common.ArtistRepository;

public class MusicGroupEditUI extends BaseJFrame {

    //private fields
    MusicGroup selectedMusicGroup;
    EntityManager entityManager;

    public MusicGroupEditUI(MusicGroup musicGroup, EntityManager entityManager) {
        this(entityManager);

        // Manually
        if (musicGroup != null) {
            this.musicGroup1.setMusicGroupId(musicGroup.getMusicGroupId());

            nameTF.setText(musicGroup.getName());
            formationDateDC.setDate(musicGroup.getFormationDate());
            musicGroup1.setArtistList(musicGroup.getArtistList());
            DefaultListModel assignedArtistsDLM = new DefaultListModel();

            for (Artist artist : musicGroup.getArtistList()) {
                assignedArtistsDLM.addElement(artist.getArtisticName());
            }

            assignedArtists.setModel(assignedArtistsDLM);
        }
    }

    public MusicGroupEditUI(EntityManager entityManager) {
        this.entityManager = entityManager;

        initComponents();

        this.musicGroup1.setArtistList(new ArrayList<>());
        this.musicGroup1.setAlbumList(new ArrayList<>());

        // display in the center of the window
        setLocationRelativeTo(null);
    }

    public MusicGroup getSelectedMusicGroup() {
        return musicGroup1;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        artistQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT a FROM Artist a");
        artistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(artistQuery.getResultList());
        musicGroup1 = new model.MusicGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        nameTF = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        formationDateDC = new com.toedter.calendar.JDateChooser();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        availableArtists = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        assignedArtists = new javax.swing.JList();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Επωνυμία συγκροτήματος");

        jLabel2.setText("Επεξεργασία συγκροτήματος");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, musicGroup1, org.jdesktop.beansbinding.ELProperty.create("${name}"), nameTF, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel3.setText("Ημερομηνία δημιουργίας");

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jButton1.setText("Εισαγωγή");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addArtists(evt);
            }
        });

        jButton2.setText("Διαγραφή");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeArtists(evt);
            }
        });

        jLabel4.setText("Διαθέσιμοι καλλιτέχνες");

        jLabel5.setText("Επιλεγμένοι καλλιτέχνες");

        org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, artistList, availableArtists);
        jListBinding.setDetailBinding(org.jdesktop.beansbinding.ELProperty.create("${artisticName}"));
        bindingGroup.addBinding(jListBinding);

        jScrollPane1.setViewportView(availableArtists);

        jScrollPane2.setViewportView(assignedArtists);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel4)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE))
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(37, 37, 37)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                    .addComponent(jScrollPane2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addGap(76, 76, 76))
        );

        jButton3.setText("Αποθήκευση");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveMusicGroup(evt);
            }
        });

        jButton4.setText("Ακύρωση");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelForm(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(187, 187, 187)
                        .addComponent(jButton3)
                        .addGap(18, 18, 18)
                        .addComponent(jButton4))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 559, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel3))
                                .addGap(151, 151, 151)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(formationDateDC, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(nameTF)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(170, 170, 170)
                        .addComponent(jLabel2)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(formationDateDC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void twoListManipulation(JList from, JList to) {
        ListModel leftLM = from.getModel();
        ListModel rightLM = to.getModel();

        int leftSelected = from.getSelectedIndex();    //index of selected Left JList item
        Object selectedItem = from.getSelectedValue(); //value of selected Left JList item

        DefaultListModel leftDLM = new DefaultListModel();  //Create new instance of DefaultListModel for left JList
        DefaultListModel rightDLM = new DefaultListModel(); //Create new instance of DefaultListModel for right JList

        //copy existing items to DefaultListModel
        for (int i = 0; i < leftLM.getSize(); i++) {
            if (i == leftSelected) {  //skip selected item
                continue;
            } else {
                leftDLM.addElement(leftLM.getElementAt(i)); //element added
            }
        }
        from.setModel(leftDLM);//set new model for left JList without "deleted" item

        //copy items from right ListModel to new DefaultListModel
        for (int i = 0; i < rightLM.getSize(); i++) {
            rightDLM.addElement(rightLM.getElementAt(i));
        }
        rightDLM.addElement(selectedItem);  //Item from left List added

        to.setModel(rightDLM);  //set new model with added item
    }

    private void addArtists(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtists

//        //Δημιουργία νέου αντικειμένου της κλάσης SelectMemberForm
//        SelectMemberForm smForm = new SelectMemberForm(entityManager, artistList, this);
//        smForm.setVisible(true);
//        smForm.setEnabled(false);

        Object availableArtist = availableArtists.getSelectedValue();
        for (int i = 0; i < assignedArtists.getModel().getSize(); i++) {
            Object elementAt = assignedArtists.getModel().getElementAt(i);
            if (elementAt != null && elementAt.equals(availableArtist)) {
                showWarningMessage("Ο καλλιτέχνης υπάρχει ήδη στην λίστα");
                return;
            }
        }
        twoListManipulation(availableArtists, assignedArtists);
    }//GEN-LAST:event_addArtists

    private void removeArtists(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeArtists

        twoListManipulation(assignedArtists, availableArtists);

    }//GEN-LAST:event_removeArtists

    private void saveMusicGroup(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMusicGroup

        if (formationDateDC.getDate() == null) {
            showWarningMessage("Δεν έχετε επιλέξει ημερομηνία");
            return;
        }

        if (assignedArtists.getModel().getSize() == 0) {
            showWarningMessage("Δεν έχετε επιλέξει καλλιτέχνες");
            return;
        }
        
        if (assignedArtists.getModel().getSize() < 2) {
            showWarningMessage("Το συγκρότημα πρέπει να διαθέτει τουλάχιστον δυο καλλιτέχνες");
            return;
        }

        musicGroup1.setFormationDate(formationDateDC.getDate());
        musicGroup1.getArtistList().clear();
        ArtistRepository artistRepository = new ArtistRepository(entityManager);
        for (int i = 0; i < assignedArtists.getModel().getSize(); i++) {
            Object item = assignedArtists.getModel().getElementAt(i);
            Artist artist = artistRepository.findByPropertyName("ArtisticName", item);
            musicGroup1.getArtistList().add(artist);
        }

        closeFrame(true);
    }//GEN-LAST:event_saveMusicGroup

    private void cancelForm(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelForm
        closeFrame(false);
    }//GEN-LAST:event_cancelForm


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Artist> artistList;
    private javax.persistence.Query artistQuery;
    private javax.swing.JList assignedArtists;
    private javax.swing.JList availableArtists;
    private com.toedter.calendar.JDateChooser formationDateDC;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private model.MusicGroup musicGroup1;
    private javax.swing.JTextField nameTF;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
